<?php
/**
 * Created by PhpStorm
 * User: ZhuYunlong2018
 * Email: 920200256@qq.com
 * Date: 2022/1/5
 * Time: 12:36
 */

namespace app\lib;

use app\admin\logic\auth\Token;
use think\App;
use think\log\driver\File;

/**
 * 扩展日志驱动文件
 * Class LogFile
 * @package app\lib
 */
class LogFile extends File
{
    /**
     * @var App
     */
    protected $app;

    public function __construct(App $app, array $config = [])
    {
        parent::__construct($app, $config);
        $this->app = $app;
    }

    /**
     * 日志写入接口
     * @access public
     * @param  array $log 日志信息
     * @param  bool $append 是否追加请求信息
     * @return bool
     */
    public function save(array $log = [], $append = false): bool
    {
        $destination = $this->getMasterLogFile();

        $path = dirname($destination);
        !is_dir($path) && mkdir($path, 0755, true);

        $info = [];

        // 日志信息封装
        $time = \DateTime::createFromFormat('0.u00 U', microtime())->setTimezone(new \DateTimeZone(date_default_timezone_get()))->format($this->config['time_format']);

        foreach ($log as $type => $val) {
            $message = [];
            foreach ($val as $msg) {
                if (!is_string($msg)) {
                    $msg = var_export($msg, true);
                }

                $message[] = $this->config['json'] ?
                    json_encode(['time' => $time, 'type' => $type, 'msg' => $msg], $this->config['json_options']) :
                    sprintf($this->config['format'], $time, $type, $msg);
            }

            if (true === $this->config['apart_level'] || in_array($type, $this->config['apart_level'])) {
                // 独立记录的日志级别
                $filename = $this->getApartLevelFile($path, $type);
                $this->write($message, $filename);
                continue;
            }

            $info[$type] = $message;
        }
        // 单独插入post日志
        $this->savePost($path);

        if ($info) {
            return $this->write($info, $destination);
        }

        return true;
    }

    /**
     * 保存post的日志
     */
    protected function savePost($path)
    {
        //写入post日志
        if (in_array($this->app['request']->method(), ['POST', 'PUT', 'DELETE'])) {
            // 记录返回正确的post请求到日志中
            $filename = $this->getApartLevelFile($path, 'post');
            $message = [
                'timestamp' => date($this->config['time_format']),
                'ip' => $this->app['request']->ip(),
                'method' => $this->app['request']->method(),
                'host' => $this->app['request']->host(),
                'uri' => $this->app['request']->url(),
                'payload' => $this->app['request']->post(),
                'query' => $this->app['request']->get(),
            ];
            if (is_array($message['payload']) && isset($message['payload']['password'])) {
                $message['payload']['password'] = "*****";
            }
            $adminId = Token::instance()->getAdminID();
            if ($adminId) {
                $message['admin_id'] = $adminId;
            }
            $message = json_encode($message, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . PHP_EOL;
            error_log($message, 3, $filename);
        }
    }
}